package com.zxy.service;

import com.zxy.dao.AdminDAO;
import com.zxy.dao.MusicDAO;
import com.zxy.model.AdminInfo;
import com.zxy.model.MusicInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class AdminServiceImpl implements AdminService {
    
    @Resource
    private MusicDAO musicDAO;
    @Resource
    private AdminDAO adminDAO;
    @Resource
    private MusicInfo musicInfo;
    
    private List<MusicInfo> getAllMusic() {
        return musicDAO.getAllMusic();
    }
    
    @Override
    public boolean checkAdminInfo(AdminInfo adminInfo) {
        return adminDAO.checkAdminInfo(adminInfo)==1;
    }
    
    @Override
    public boolean deleteMusic(String musicName) {
        return musicDAO.deleteMusic(musicName)==1;
    }
    
    @Override
    public boolean musicIsExist(MusicInfo musicInfo) {
        return musicDAO.musicIsExist(musicInfo)==1;
    }
    
    @Override
    public void insert(MusicInfo musicInfo) {
        musicDAO.insert(musicInfo);
    }
    
    @Override
    public void updateMusic(String path) {
        List<MusicInfo> oldList=getAllMusic();//旧的音乐列表
        List<String> pathList=new ArrayList<>();
    
        File fList[] = new File(path).listFiles();
        for (File file : fList) {
            pathList.add(file.getPath());
        }
    
        for (String s : pathList) {
            Pattern p=Pattern.compile("(?<=music.).+(?=.mp3)");//验证文件名是否合法
            Matcher m=p.matcher(s);
            String name;
            if (m.find()){
                name=m.group();
                musicInfo.setMusicName(name);
                musicInfo.setMusicPath("music/"+name+".mp3");
                if (oldList.contains(musicInfo)){
                    continue;//如果旧的音乐列表已有此音乐对象，跳过
                }
                insert(musicInfo);
            }
        }
    }
}
